<template>
  <div class="barcode-print-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>条码打印系统</span>
      </div>

      <!-- 单个条码打印区域 -->
      <div class="single-print">
        <h3>单个条码打印</h3>
        <el-form :inline="true" :model="singleForm" class="demo-form-inline">
          <el-form-item label="条码内容">
            <el-input
              v-model="singleForm.barcode"
              placeholder="请输入条码内容"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="printSingleBarcode"
              >打印单个条码</el-button
            >
          </el-form-item>
        </el-form>
        <div id="onPrint"></div>
      </div>

      <!-- 批量条码打印区域 -->
      <div class="batch-print">
        <h3>批量条码打印</h3>
        <el-form :inline="true" :model="batchForm" class="demo-form-inline">
          <el-form-item label="条码前缀">
            <el-input
              v-model="batchForm.prefix"
              placeholder="请输入条码前缀"
            ></el-input>
          </el-form-item>
          <el-form-item label="起始数字">
            <el-input-number
              v-model="batchForm.startNum"
              :min="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item label="结束数字">
            <el-input-number
              v-model="batchForm.endNum"
              :min="1"
            ></el-input-number>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="previewBatchBarcodes"
              >预览批量条码</el-button
            >
            <el-button type="success" @click="printBatchBarcodes"
              >直接打印批量条码</el-button
            >
          </el-form-item>
        </el-form>
      </div>

      <!-- 批量预览区域 -->
      <div class="preview-area" v-if="showPreview">
        <h3>批量条码预览</h3>
        <div class="barcode-list">
          <div
            v-for="(barcode, index) in barcodeList"
            :key="index"
            class="barcode-item"
          >
            <div :id="`barcode-${index}`" class="barcode-container"></div>
            <div class="barcode-text">{{ barcode }}</div>
          </div>
        </div>
        <div class="preview-actions">
          <el-button type="primary" @click="printPreviewBarcodes"
            >打印预览条码</el-button
          >
          <el-button @click="closePreview">关闭预览</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { hiprint } from "vue-plugin-hiprint";

export default {
  name: "hiPrintDome",
  data() {
    return {
      singleForm: {
        barcode: "",
      },
      batchForm: {
        prefix: "",
        startNum: 1,
        endNum: 10,
      },
      barcodeList: [],
      showPreview: false,
      hiprintTemplate: null,
    };
  },
  mounted() {
    // 初始化打印模板
    this.initPrintTemplate();
  },
  methods: {
    // 初始化打印模板
    initPrintTemplate() {
      // 创建条码打印模板
      this.hiprintTemplate = new hiprint.PrintTemplate({
        template: {
          panels: [
            {
              index: 0,
              name: 1,
              height: 30,
              width: 50,
              paperHeader: 0,
              paperFooter: 85.03937007874016,
              printElements: [
                {
                  options: {
                    left: 13.5,
                    top: 9,
                    height: 10.5,
                    width: 127,
                    title: "Black L Barck...Swith Screws",
                    right: 139.75,
                    bottom: 18.75,
                    vCenter: 76.25,
                    hCenter: 13.5,
                    coordinateSync: false,
                    widthHeightSync: false,
                    fontSize: 9,
                    textContentVerticalAlign: "middle",
                    textContentWrap: "nowrap",
                    qrCodeLevel: 0,
                  },
                  printElementType: {
                    title: "文本",
                    type: "text",
                  },
                },
                {
                  options: {
                    left: 19.5,
                    top: 24,
                    height: 30,
                    width: 105,
                    field: "barcode",
                    testData: "XS888888888",
                    fontSize: 9,
                    textType: "barcode",
                    title: "条形码",
                    qid: "barcode",
                    right: 118.5,
                    bottom: 54.75,
                    vCenter: 66,
                    hCenter: 39.75,
                    coordinateSync: false,
                    widthHeightSync: false,
                    qrCodeLevel: 0,
                    textAlign: "center",
                  },
                  printElementType: {
                    title: "条形码",
                    type: "text",
                  },
                },
                {
                  options: {
                    left: 7.5,
                    top: 57,
                    height: 12,
                    width: 120,
                    title: "MADE IN CHINA",
                    right: 123.75,
                    bottom: 72,
                    vCenter: 63.75,
                    hCenter: 66,
                    coordinateSync: false,
                    widthHeightSync: false,
                    textAlign: "center",
                    qrCodeLevel: 0,
                    fontSize: 9,
                  },
                  printElementType: {
                    title: "文本",
                    type: "text",
                  },
                },
                {
                  options: {
                    left: 7.5,
                    top: 67.5,
                    height: 9.75,
                    width: 30,
                    title: "NEW",
                    coordinateSync: false,
                    widthHeightSync: false,
                    fontSize: 9,
                    qrCodeLevel: 0,
                  },
                  printElementType: {
                    title: "文本",
                    type: "text",
                  },
                },
                {
                  options: {
                    left: 102,
                    top: 67.5,
                    height: 9.75,
                    width: 37.5,
                    title: "AGDE",
                    right: 138.75,
                    bottom: 75.75,
                    vCenter: 120,
                    hCenter: 70.875,
                    coordinateSync: false,
                    widthHeightSync: false,
                    fontSize: 9,
                    qrCodeLevel: 0,
                  },
                  printElementType: {
                    title: "文本",
                    type: "text",
                  },
                },
              ],
              paperNumberLeft: 111,
              paperNumberTop: 63,
              paperNumberDisabled: true,
              paperNumberContinue: true,
              watermarkOptions: {
                content: "",
                fillStyle: "rgba(184, 184, 184, 0.3)",
                fontSize: "14px",
                rotate: 25,
                width: 200,
                height: 200,
                timestamp: false,
                format: "YYYY-MM-DD HH:mm",
              },
              panelLayoutOptions: {
                layoutType: "column",
                layoutRowGap: 0,
                layoutColumnGap: 0,
              },
            },
          ],
        },
      });
    },

    // 打印单个条码
    printSingleBarcode() {
      if (!this.singleForm.barcode) {
        this.$message.warning("请输入条码内容");
        return;
      }

      const printData = {
        barcode: this.singleForm.barcode,
      };
      // this.hiprintTemplate.printByHtml($('#onPrint').html())
      // console.log("info",this.hiprintTemplate)
      // return

      this.hiprintTemplate.print(printData);
    },

    // 生成批量条码数据
    generateBatchBarcodes() {
      const { prefix, startNum, endNum } = this.batchForm;
      const barcodes = [];

      if (!prefix) {
        this.$message.warning("请输入条码前缀");
        return [];
      }

      if (startNum > endNum) {
        this.$message.warning("起始数字不能大于结束数字");
        return [];
      }

      for (let i = startNum; i <= endNum; i++) {
        barcodes.push(`${prefix}${i}`);
      }

      return barcodes;
    },

    // 预览批量条码
    previewBatchBarcodes() {
      this.barcodeList = this.generateBatchBarcodes();

      if (this.barcodeList.length === 0) {
        return;
      }

      this.showPreview = true;

      // 等待DOM更新后渲染条码
      this.$nextTick(() => {
        this.barcodeList.forEach((barcode, index) => {
          const elementId = `barcode-${index}`;
          const element = document.getElementById(elementId);

          if (element) {
            // 清空容器
            element.innerHTML = "";

            // 渲染条码
            const printData = { barcode };
            this.hiprintTemplate.design(element, printData);
          }
        });
      });
    },

    // 打印批量条码
    printBatchBarcodes() {
      this.barcodeList = this.generateBatchBarcodes();

      if (this.barcodeList.length === 0) {
        return;
      }

      // 准备批量打印数据
      const printDataList = this.barcodeList.map((barcode) => ({ barcode }));

      // 执行批量打印
      this.hiprintTemplate.print(printDataList);
    },

    // 打印预览的条码
    printPreviewBarcodes() {
      if (this.barcodeList.length === 0) {
        return;
      }

      // 准备批量打印数据
      const printDataList = this.barcodeList.map((barcode, index) => ({
        barcode,
        index,
      }));
      console.log("printDataList", printDataList);

      // // 执行批量打印
      this.hiprintTemplate.print(printDataList);

      // 遍历打印数据列表，逐个打印
      // this.barcodeList.forEach((data, index) => {
      //   // 可以添加延迟，防止打印队列冲突
      //   setTimeout(() => {
      //     this.hiprintTemplate.print(data, {
      //       // 打印选项
      //       printer: "", // 指定打印机名称，留空则使用默认打印机
      //       title: `批量打印_${index + 1}`,
      //     });
      //   }, index * 1000); // 每个打印间隔1秒
      // });
    },

    // 关闭预览
    closePreview() {
      this.showPreview = false;
    },
  },
};
</script>

<style scoped>
.barcode-print-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.single-print,
.batch-print {
  margin-bottom: 30px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.preview-area {
  margin-top: 30px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.barcode-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.barcode-item {
  border: 1px solid #ebeef5;
  padding: 10px;
  border-radius: 4px;
  width: 120px;
  text-align: center;
}

.barcode-container {
  height: 40px;
  margin-bottom: 5px;
}

.barcode-text {
  font-size: 12px;
  word-break: break-all;
}

.preview-actions {
  text-align: center;
  margin-top: 20px;
}
</style>
